using Devtodo.Models;
using Microsoft.Data.Sqlite;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using System;
using System.Collections.ObjectModel;
using Windows.Storage;
namespace Devtodo.Pages;

public sealed partial class Version : Page
{
  public Version()
  {
    InitializeComponent();
    LoadProjectList();
  }
  public ObservableCollection<VersionItem> Items { get; } = [];
  public ObservableCollection<string> ProjectNames { get; set; } = [];
  int UpdateId { get; set; } = -1;
  async void LoadList()
  {
    Items.Clear();
    var connection = new SqliteConnection("Data Source=" + ApplicationData.Current.LocalFolder.Path + "/devtodo.db");
    await connection.OpenAsync();
    var selectVersionCmd = new SqliteCommand("SELECT * FROM version WHERE projectid=" + GetProjectId(Project.SelectedValue.ToString()), connection);
    var versionReader = await selectVersionCmd.ExecuteReaderAsync();
    while (await versionReader.ReadAsync())
    {
      Items.Add(new VersionItem
      {
        Id = versionReader.GetInt32(0),
        Version = versionReader.GetString(2)
      });
    }
    await connection.CloseAsync();
  }
  async void LoadProjectList()
  {
    var connection = new SqliteConnection("Data Source=" + ApplicationData.Current.LocalFolder.Path + "/devtodo.db");
    await connection.OpenAsync();
    var selectProjectCmd = new SqliteCommand("SELECT name FROM project", connection);
    var projectReader = await selectProjectCmd.ExecuteReaderAsync();
    while (await projectReader.ReadAsync())
    {
      ProjectNames.Add(projectReader.GetString(0));
    }
    await connection.CloseAsync();
    Project.ItemsSource = ProjectNames;
    Project.SelectedItem = ProjectNames[0];
    LoadList();
  }
  static int GetProjectId(string ProjectName)
  {
    var connection = new SqliteConnection("Data Source=" + ApplicationData.Current.LocalFolder.Path + "/devtodo.db");
    connection.Open();
    var selectCmd = new SqliteCommand("SELECT id FROM project WHERE name='" + ProjectName + "'", connection);
    var reader = selectCmd.ExecuteReader();
    if (reader.Read())
    {
      var projectId = reader.GetInt32(0);
      connection.Close();
      return projectId;
    }
    connection.Close();
    return -1;
  }
  void ChangeProject(object sender, SelectionChangedEventArgs args)
  {
    LoadList();
  }
  void Back()
  {
    List.Visibility = Visibility.Visible;
    New.Visibility = Visibility.Collapsed;
    Update.Visibility = Visibility.Collapsed;
    UpdateId = -1;
    InsertVersionInput.Text = "";
    UpdateVersionInput.Text = "";
    LoadList();
  }
  void NavigateToNew(object sender, RoutedEventArgs args)
  {
    List.Visibility = Visibility.Collapsed;
    New.Visibility = Visibility.Visible;
    Update.Visibility = Visibility.Collapsed;
  }
  void NavigateToUpdate(object sender, RoutedEventArgs args)
  {
    if (sender is Button btn)
    {
      var e = (VersionItem)btn.Tag;
      UpdateId = e.Id;
      UpdateVersionInput.Text = e.Version;
    }
    List.Visibility = Visibility.Collapsed;
    New.Visibility = Visibility.Collapsed;
    Update.Visibility = Visibility.Visible;
  }
  void NavigateBack(object sender, RoutedEventArgs args)
  {
    Back();
  }
  async void NewVersion(object sender, RoutedEventArgs args)
  {
    try
    {
      if (InsertVersionInput.Text.Length == 0)
      {
        ContentDialog dialog = new()
        {
          XamlRoot = XamlRoot,
          Title = "提示",
          Content = "请输入版本号",
          PrimaryButtonText = "确定",
          DefaultButton = ContentDialogButton.Primary
        };
        await dialog.ShowAsync();
        return;
      }
      var connection = new SqliteConnection("Data Source=" + ApplicationData.Current.LocalFolder.Path + "/devtodo.db");
      await connection.OpenAsync();
      var incertCmd = new SqliteCommand("INSERT INTO version (projectid, version) VALUES (" + GetProjectId(Project.SelectedValue.ToString()) + ",'" + InsertVersionInput.Text + "')", connection);
      await incertCmd.ExecuteNonQueryAsync();
      await connection.CloseAsync();
      ContentDialog successDialog = new()
      {
        XamlRoot = XamlRoot,
        Title = "提示",
        Content = "新增成功",
        PrimaryButtonText = "确定",
        DefaultButton = ContentDialogButton.Primary
      };
      await successDialog.ShowAsync();
      Back();
    }
    catch (Exception err)
    {
      ContentDialog dialog = new()
      {
        XamlRoot = XamlRoot,
        Title = "错误",
        Content = err.Message,
        PrimaryButtonText = "确定",
        DefaultButton = ContentDialogButton.Primary
      };
      await dialog.ShowAsync();
    }
  }
  async void UpdateVersion(object sender, RoutedEventArgs args)
  {
    try
    {
      if (UpdateVersionInput.Text.Length == 0)
      {
        ContentDialog dialog = new()
        {
          XamlRoot = XamlRoot,
          Title = "提示",
          Content = "请输入版本号",
          PrimaryButtonText = "确定",
          DefaultButton = ContentDialogButton.Primary
        };
        await dialog.ShowAsync();
        return;
      }
      var connection = new SqliteConnection("Data Source=" + ApplicationData.Current.LocalFolder.Path + "/devtodo.db");
      await connection.OpenAsync();
      var updateCmd = new SqliteCommand("UPDATE version SET version='" + UpdateVersionInput.Text + "' WHERE id=" + UpdateId, connection);
      await updateCmd.ExecuteNonQueryAsync();
      await connection.CloseAsync();
      ContentDialog successDialog = new()
      {
        XamlRoot = XamlRoot,
        Title = "提示",
        Content = "修改成功",
        PrimaryButtonText = "确定",
        DefaultButton = ContentDialogButton.Primary
      };
      await successDialog.ShowAsync();
      Back();
    }
    catch (Exception err)
    {
      ContentDialog dialog = new()
      {
        XamlRoot = XamlRoot,
        Title = "错误",
        Content = err.Message,
        PrimaryButtonText = "确定",
        DefaultButton = ContentDialogButton.Primary
      };
      await dialog.ShowAsync();
    }
  }
}